//
// File: console.cpp
// Description: 
//

#include <iostream>
#include <string>

using namespace std;

#include "protocol.h"
#include "socket.h"


int main(int argc, char **argv) {
	
	
	if (argc < 3) {
		cerr << "Usage: " << argv[0] << " hostname port" << endl;
		exit(0);
	}

	string host(argv[1]);
	ClientSocket client(host, atoi(argv[2]));
	
	bool loggedIn = false;
	while (!loggedIn) {
		cout << "0 to login, 1 to create account, 2 to quit: ";
		char buf[32];
		cin.getline(buf, 32);
		
		switch(atoi(buf)) {
			case 0: {
				// Attempt to log in
				dHeader h(LOGIN_REQUEST, sizeof(dLoginRequest));
				dLoginRequest login;
				dLoginResponse res;
				
				cout << "Username: ";
				cin.getline(login.username, 32);
				
				cout << "Password: ";
				cin.getline(login.password, 32);
				
				client.send(&h, sizeof(dHeader));
				client.send(&login, sizeof(dLoginRequest));
				
				// wait for response
				int n = client.recv(&res, sizeof(res));
				
				switch (res.type) {
					case SUCCESS: {
						cout << "You have logged in" << endl;
						loggedIn = true;
						break;
					}
					case BAD_PASSWORD: {
						cout << "Password is invalid for user" << endl;
						break;
					}
					case USER_DOESNT_EXIST: {
						cout << "Username doesn't exist" << endl;
						break;
					}
				}
				
				break;
			}
			case 1: {
				// Attempt to crate account
				dHeader h(CREATE_ACCOUNT, sizeof(dCreateAccount));
				dCreateAccount login;
				dCreateResponse res;
				
				cout << "Username: ";
				cin.getline(login.username, 32);
				
				cout << "Password: ";
				cin.getline(login.password, 32);
				
				client.send(&h, sizeof(dHeader));
				client.send(&login, sizeof(dLoginRequest));
				
				// get response
				int n = client.recv(&res, sizeof(res));
				switch (res.type) {
					case SUCCESS: {
						cout << "Account has been created" << endl;
						break;
					}
					case USER_NAME_TAKEN: {
						cout << "The username is taken" << endl;
						break;
					}
				}
				break;
			}
			case 2:
				client.close();
				client.closeWinsock();
				exit(1);
				break;
		}
		
	}
	
	bool running = true;
	char buf[512];
	while (running) {
		cout << ">>";
		cin.getline(buf, 512);
		
		
		
	}

	
	client.close();
	client.closeWinsock();
}
